<?php

namespace Admin\Model;

use Think\Model;

class AdminUserModel extends Model{
	protected $_validate = array(
			//array(验证字段,验证规则,错误提示,验证条件,附加规则,验证时间)
			array('username', 'require', '用户名称不能为空！', 1, 'regex', Model:: MODEL_INSERT  ),
			array('password', 'require', '密码不能为空！', 1, 'regex', Model:: MODEL_INSERT ),
			array('username','','用户名已经存在！',0,'unique',Model:: MODEL_BOTH ), // 验证user_login字段是否唯一
	);
	
	protected function _before_write(&$data) {
		parent::_before_write($data);
	
		if(!empty($data['password']) && strlen($data['password'])<25){
			$data['password']=hashPassword($data['password']);
		}
	}
	
	protected function _before_insert(&$data) {
		parent::_before_insert($data);
		
		$data ['status'] = 1;
	}
	
	public function login($username, $password) {
		$userObject = null;
		
		$userObject = $this->findByUsername($username);
		if (!$userObject) {
			return false;
		}
		
		$verifyResult = checkPassword($password, $userObject ['password']);
		if (!$verifyResult) {
			return false;
		}
		
		return $userObject;
	}
	
	public function findByUsername($username) {
		return $this->where(array('username' => $username))->find();
	}
}